//
//  AutoRefreshTableView.m
//  SafePeriod
//
//  Created by Sheng long on 13-6-5.
//  Copyright (c) 2013年 cdeledu. All rights reserved.
//

#import "AutoRefreshTableView.h"
#import "AutoTableConstant.h"
#import "AutoRefreshTableHeaderView.h"
#import "AutoLoadingMoreView.h"

#define SelfSafeRelease(_v) if(_v != nil){ [_v release]; _v = nil;}

//设置上拉刷新Y坐标，内容大小与实际大小做比较
#define mainTable_height  _mainTable.contentSize.height > _mainTable.frame.size.height ? _mainTable.contentSize.height : _mainTable.frame.size.height

@interface AutoRefreshTableView()<EGORefreshTableHeaderDelegate,AutoLoadingMoreViewDelegate>
{
    //获取当前刷新类型
    TABEL_REFRESH_STATE _currentRefreshState;
    
    //当前刷新
    AutoRefreshTableHeaderView *_refreshHeaderView;
    //下拉刷新
	AutoRefreshTableHeaderView *down_refreshHeaderView;
    //标志是否正在刷新
	BOOL _reloading;
    
    //加载更多
    AutoLoadingMoreView *customLoadingDataView;
}
@end

@implementation AutoRefreshTableView

@synthesize delegate,mainTable=_mainTable;
@synthesize autoDataArray=_autoDataArray,getDataNumber;
@synthesize currentRefreshState=_currentRefreshState;

-(void)dealloc
{
    if (down_refreshHeaderView) {
        down_refreshHeaderView.delegate = nil;
        SelfSafeRelease(down_refreshHeaderView)
    }
    SelfSafeRelease(customLoadingDataView)
    SelfSafeRelease(_autoDataArray)
    SelfSafeRelease(_mainTable)
    [super dealloc];
}

//自定义初始化方法
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // Initialization code
        _mainTable = [[UITableView alloc]initWithFrame:self.bounds];
        [_mainTable setDelegate:self];
        [_mainTable setDataSource:self];
        [_mainTable setBackgroundColor:[UIColor clearColor]];
        [_mainTable setSeparatorColor:[UIColor clearColor]];
        [self addSubview:_mainTable];
    }
    return self;
}

//设置刷新获取数据view
-(void)setCurrentRefreshType:(TABEL_REFRESH_STATE)type
{
    //获取刷新view
    BOOL isDown = NO;
    BOOL isOn = NO;
    switch (type) {
        case NO_REFRESH_STATE:
        {
            //没有刷新
        }
            break;
        case REFRESH_STATE:
        {
            //下拉
            isDown = YES;
        }
            break;
        case LOADING_MORE_STATE:
        {
            //上拉
            isOn = YES;
        }
            break;
        case ALL_REFRESH_STATE:
        {
            //上下拉取
            isDown = YES;
            isOn = YES;
        }
            break;
        default:
            break;
    }
    
    if (YES == isDown && !down_refreshHeaderView) {
        //下拉
        down_refreshHeaderView = [[AutoRefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _mainTable.bounds.size.height, self.frame.size.width, _mainTable.bounds.size.height) state:downPullState];
        down_refreshHeaderView.delegate = self;
        [_mainTable addSubview:down_refreshHeaderView];
        [down_refreshHeaderView refreshLastUpdatedDate];
    }
    
    if (YES == isOn && !customLoadingDataView) {
        //设置默认状态
        customLoadingDataView = [[AutoLoadingMoreView alloc]initWithFrame:CGRectMake(0.0, 0.0,  self.frame.size.width, 40.0)];
        [customLoadingDataView setDelegate:self];
    }
}

//设置数据源，同时设置加载更多数据的显示
-(void)setAutoDataArray:(NSArray *)aArray
{
    NSInteger oldDataNumber = _autoDataArray.count;
    
    if (customLoadingDataView) {
        //是否没有更多数据可加载
        BOOL noData = NO;
        if ((_currentRefreshState == LOADING_MORE_STATE) && (aArray.count-oldDataNumber<getDataNumber)) {
            //加载更多数据加载完成
            noData = YES;
        }else if (aArray.count<getDataNumber) {
            noData = YES;
        }
        if (noData) {
            //此情况一般说明没有更多数据可用加载了
            [customLoadingDataView setCurrentDataState:AlreadyLoadedState];
            if (TABLE_REFRESH_MORE_DATA_SHOW) {
                //提示无更多数据加载
                [_mainTable setTableFooterView:customLoadingDataView];
            }else{
                [_mainTable setTableFooterView:nil];
            }
        }else{
            //显示加载更多数据
            [customLoadingDataView setCurrentDataState:GetMoreDataState];
            [_mainTable setTableFooterView:customLoadingDataView];
        }
    }
    
    //刷新数据
    SelfSafeRelease(_autoDataArray)
    _autoDataArray = [aArray retain];
    [self doneLoadingTableViewData];
}

//自动刷新数据
-(void)autoPullGetData
{
    if (!_reloading) {
        [self performSelector:@selector(autoS) withObject:nil afterDelay:0.1];
    }
}
-(void)autoS
{
    [down_refreshHeaderView autoRefreshData:_mainTable];
}

//获取数据异常状态调用此方法
//恢复之前显示状态
-(void)recoverShowState
{
    if (_currentRefreshState == LOADING_MORE_STATE) {
        //设置加载更多状态异常
        [customLoadingDataView setCurrentDataState:GetMoreDataExceptionState];
    }
    [self doneLoadingTableViewData];
}

#pragma mark - 执行获取数据的方法
//刷新数据
-(void)refreshData
{
    if ([self.delegate respondsToSelector:@selector(refreshTableData)]) {
        //正在下拉刷新
        [self.delegate refreshTableData];
    }else{
        [self doneLoadingTableViewData];
    }
}

//点击加载更多
-(void)loadingMoreData
{
    BOOL use = NO;
    if (TABLE_REFRESH_MORE_DATA_MODE || !_reloading) {
        use = YES;
    }
    
    if ([self.delegate respondsToSelector:@selector(loadingMoreTableData)] && use) {
        //正在加载更多
        _reloading = YES;
        _currentRefreshState = LOADING_MORE_STATE;
        [self.delegate loadingMoreTableData];
    }else{
        [customLoadingDataView setCurrentDataState:GetMoreDataState];
    }
}

//获取获取数据完成
-(void)doneLoadingTableViewData
{
    //修改EGORefreshTableHeaderView状态和位置信息
    if (_currentRefreshState == REFRESH_STATE) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_mainTable];
    }
    
    _reloading = NO;
    _currentRefreshState = NO_REFRESH_STATE;
    
    //完成刷新UI
    [_mainTable reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

#pragma mark - UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    NSLog(@"%d",(scrollView.contentSize.height - scrollView.contentOffset.y -scrollView.bounds.size.height < customLoadingDataView.bounds.size.height));
    //当前正在刷新
    if (!_reloading) {
        //        NSLog(@"yes");
        if (scrollView.contentOffset.y<0) {
            //处于下拉状态
            _refreshHeaderView = down_refreshHeaderView;
            [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        }else if(TABLE_REFRESH_MORE_DATA_MODE && customLoadingDataView.currentDataState==GetMoreDataState && (scrollView.contentSize.height - scrollView.contentOffset.y -scrollView.bounds.size.height < customLoadingDataView.bounds.size.height)){
            //需要自动刷新
            _reloading = YES;
            [customLoadingDataView clickButt];
        }else if (customLoadingDataView.currentDataState == GetMoreDataExceptionState && (scrollView.contentSize.height - scrollView.contentOffset.y -scrollView.bounds.size.height > customLoadingDataView.bounds.size.height)){
            //加载更多异常状态
            //重新设置为加载更多状态
            customLoadingDataView.currentDataState = GetMoreDataState;
        }
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //    NSLog(@"scrollViewDidEndDragging");
    //当前正在刷新
    if (!_reloading) {
        //停止拖动调用此方法
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}

#pragma mark - EGORefreshTableHeaderDelegate Methods
//代理执行获取数据的方法
- (void)egoRefreshTableHeaderDidTriggerRefresh:(AutoRefreshTableHeaderView*)view
{
    //网络状态不佳的情况下会卡死，开线程去执行方法
    //设置正在刷新状态
	_reloading = YES;
    
    //根据拉取状态执行获取数据的方法
    if ([_refreshHeaderView isEqual:down_refreshHeaderView]) {
        //刷新数据
        _currentRefreshState = REFRESH_STATE;
        [self refreshData];
    }
}
//获取是否在刷新获取数据
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(AutoRefreshTableHeaderView*)view
{
	return _reloading;
}
//是否显示时间
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(AutoRefreshTableHeaderView*)view
{
	return [NSDate date];
}

@end
